<template>
    <div class="login-container">
        <div class="bg-left"></div>
        <div class="bg-right"></div>
        <div class="login-content">
            <img style="height: 75px;" src="@/assets/images/logo.png" alt="logo" />
            <div class="sub-title">模板系统,内部使用</div>
            <div class="ivu-login">
                <div class="demo-login">
                    <Login @on-submit="handleSubmit">
                        <Mobile placeholder="请输入手机号" name="username" value="18915974631" :rules="userNameConfirmRule" />
                        <Password name="password" value="120130" :rules="passwordConfirmRule" />
                        <Submit style="margin-top: 10px;" />
                    </Login>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { Message } from 'view-ui-plus'
import { login } from '@/api/user'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()

// 验证提示
const userNameConfirmRule = [
    { required: true, message: '请输入手机号', trigger: 'blur' },
]
const passwordConfirmRule = [
    { required: true, message: '请输入密码', trigger: 'blur' },
]

// 登录逻辑
const handleSubmit = async (valid, data) => {
    if (!valid) return Message.error('请检查输入是否正确')
    try {
        const result = await login(data)
        userStore.setToken(result.token)
        userStore.setUserInfo(result.user)
        // 获取菜单并生成路由
        await userStore.getMenus()
        Message.success('登录成功')
        router.replace('/')
    } catch (error) {
        console.error('登录失败:', error)
    }
}
</script>

<style lang="scss" scoped>
@use './index.scss';
</style>